package com.yecheng.chapter01.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;

public class MyRealm3 implements Realm{

	/**
	 * 验证用户名、密码
	 */
	@Override
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		//1、用户名
		String username = (String)token.getPrincipal();
		//2、密码(注意String的类型转换)
		String password = new String((char[])token.getCredentials());;
		//3、进行认证
		if(!"li".equals(username)){
			//抛出用户名不存在错误
			throw new UnknownAccountException();
		}
		//注释掉，也就是只要用户名是li就认证通过，用于测试AtLeastTwoAuthenticatorStrategy
//		if(!"123".equals(password)){
//			//抛出密码错误
//			throw new IncorrectCredentialsException();
//		}
		//4、认证成功，返回一个AuthenticationInfo实现
		return new SimpleAuthenticationInfo(username+"@gmail.com", password, getName());
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "MyRealm3";
	}
	
	//判断是否支持该realm
	@Override
	public boolean supports(AuthenticationToken token) {
		//仅支持UsernamePasswordToken 类型的Token
		return token instanceof UsernamePasswordToken;
	}

}
